<template>
    <div>
        <div class="input">
            <div>
                <span>课程名称：</span>
                <el-input class="shuru" v-model="courseName" placeholder="请输入内容"></el-input>
            </div>
            <div class="block">
                <span class="demonstration">创建时间：</span>
                <el-date-picker
                        v-model="value1"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">

                </el-date-picker>
                <el-button style="margin-left: 10px" @click="search" type="primary">搜索</el-button>
            </div>

        </div>

        <el-button type="primary" @click="openModal">添加</el-button>

        <el-dialog title="添加" :visible.sync="dialogFormVisible">
            <el-form :model="courseFormData">
                <el-form-item label="课程名称" :label-width="formLabelWidth">
                    <el-input v-model="courseFormData.courseName" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="课程介绍" :label-width="formLabelWidth">
                    <el-input
                            v-model="courseFormData.courseIntroduce"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>
                <el-form-item label="课件数量" :label-width="formLabelWidth">
                    <el-input v-model="courseFormData.courseMount" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="适用人群" :label-width="formLabelWidth">
                    <el-input v-model="courseFormData.applicablePopulation" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-form-item label="上传图片" :label-width="formLabelWidth">
                        <el-upload
                                class="avatar-uploader"
                                action="http://localhost:8080/course/fileup"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                                style="width: 150px ;height :150px"
                        >
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>

                    </el-form-item>
                </el-form-item>

                <el-form-item>
                <el-form-item label="上传视频" :label-width="formLabelWidth">
                    <el-upload
                            class="avatar-uploader"
                            action="http://localhost:8080/course/fileup"
                    :show-file-list="false"
                    :on-success="handleVideoSuccess"
                    :before-upload="beforeVideoUpload"
                    accept="video/mp4,video/x-m4v,video/*"
                    style="width: 150px; height: 150px"
                    >
                    <video v-if="videoUrl" :src="videoUrl" class="video-preview" controls style="width: 100%; height: 100%;"></video>
                    <i v-else class="el-icon-plus video-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                </el-form-item>

                <el-form-item label="课程时长" :label-width="formLabelWidth">
                    <el-input
                            v-model="courseFormData.courseTime"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>

                <el-form-item label="课程售价" :label-width="formLabelWidth">
                    <el-input
                            v-model="courseFormData.coursePrice"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>


                <el-form-item label="课程分类" :label-width="formLabelWidth">
                    <el-select v-model="courseFormData.type_id" placeholder="请选择">
                        <el-option
                                v-for="item in courseType"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>

                </el-form-item>

                <el-form-item label="学习收获" :label-width="formLabelWidth">
                    <el-input
                            v-model="courseFormData.learnHarvest"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>

                <el-form-item label="订阅须知" :label-width="formLabelWidth">
                    <el-input
                            v-model="courseFormData.subscriptionNotice"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>

                <el-form-item label="咨询师" :label-width="formLabelWidth">
                    <el-select v-model="courseFormData.teacher_id" placeholder="请选择">
                        <el-option
                                v-for="item in teacher"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleAdd">确 定</el-button>
            </div>
        </el-dialog>

        <el-table :data="courseTableData" style="width: 100%">
            <el-table-column prop="coursename" label="课程标题" width="150" align="center"></el-table-column>


            <el-table-column prop="tabularchart" label="图片" width="150" align="center">
                <template slot-scope="scope">
                    <div class="img-container" @click="showImage(scope.row.tabularchart)">
                        <img :src="scope.row.tabularchart"/>
                    </div>
                </template>
            </el-table-column>

            <el-table-column prop="applicablepopulation" label="课程简介" width="150" align="center"></el-table-column>
            <el-table-column prop="coursetype.name" label="课程分类" width="150" align="center"></el-table-column>

            <el-table-column prop="teacher.name" label="咨询师" width="150" align="center"></el-table-column>


                        <el-table-column label="课程视频" width="120">
                            <template slot-scope="scope">
                                <video
                                        controls
                                        @click.stop="openVideoDialog(scope.row.coursevideo)"
                                        style="width: 100%; height: auto; cursor: pointer;"
                                >
                                    <source :src="scope.row.coursevideo" type="video/mp4"/>
                                    您的浏览器不支持 HTML5 video 标签。
                                </video>
                            </template>
                        </el-table-column>


            <!--            <el-table-column prop="tabularchart" label="课程视频" width="120"></el-table-column>-->
            <!--            <el-table-column prop="coursetime" label="课程时长"></el-table-column>-->

            <el-table-column prop="createtime" label="创建时间" width="160" align="center"></el-table-column>
            <el-table-column prop="updatetime" label="修改时间" width="160" align="center"></el-table-column>

            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" @click="updateCourse(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog title="修改" :visible.sync="dialogFormVisible2">
            <el-form :model="courseFormData2">
                <el-form-item label="课程名称" :label-width="formLabelWidth">
                    <el-input v-model="courseFormData2.coursename" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="课程介绍" :label-width="formLabelWidth">
                    <el-input
                            v-model="courseFormData2.courseintroduce"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>
                <el-form-item label="课件数量" :label-width="formLabelWidth">
                    <el-input v-model="courseFormData2.coursemount" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="适用人群" :label-width="formLabelWidth">
                    <el-input v-model="courseFormData2.applicablepopulation" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-form-item label="上传图片" :label-width="formLabelWidth">
                        <el-upload
                                class="avatar-uploader"
                                action="http://localhost:8080/course/fileup"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess2"
                                :before-upload="beforeAvatarUpload2"
                                style="width: 150px ;height :150px"
                        >

                            <img v-if="courseFormData2.tabularchart" :src="courseFormData2.tabularchart" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-form-item>

                <el-form-item>
                    <el-form-item label="上传视频" :label-width="formLabelWidth">
                        <el-upload
                                class="avatar-uploader"
                                action="http://localhost:8080/course/fileup"
                                :show-file-list="false"
                                :on-success="handleVideoSuccess2"
                                :before-upload="beforeVideoUpload2"
                                accept="video/mp4,video/x-m4v,video/*"
                                style="width: 150px; height: 150px"
                        >
                            <video v-if="courseFormData2.coursevideo" :src="courseFormData2.coursevideo" class="video-preview" controls style="width: 100%; height: 100%;"></video>
                            <i v-else class="el-icon-plus video-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-form-item>



                <el-form-item label="课程时长" :label-width="formLabelWidth">
                    <el-input
                            v-model="courseFormData2.coursetime"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>

                <el-form-item label="课程售价" :label-width="formLabelWidth">
                    <el-input
                            v-model="courseFormData2.courseprice"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>

                <el-form-item label="课程分类" :label-width="formLabelWidth">

                    <el-select v-model="courseFormData2.typeId" placeholder="请选择">
                        <el-option
                                v-for="item in courseType"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>

                </el-form-item>

                <el-form-item label="学习收获" :label-width="formLabelWidth">
                    <el-input
                            v-model="courseFormData2.learnharvest"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>

                <el-form-item label="订阅须知" :label-width="formLabelWidth">
                    <el-input
                            v-model="courseFormData2.subscriptionnotice"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>

                <el-form-item label="咨询师" :label-width="formLabelWidth">
                    <el-select v-model="courseFormData2.teacherId" placeholder="请选择">
                        <el-option
                                v-for="item in teacher"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible2 = false">取 消</el-button>
                <el-button type="primary" @click="handleUpdate">确 定</el-button>
            </div>
        </el-dialog>


        <!-- 模态框 -->
        <el-dialog :visible.sync="dialogVisible" width="30%">
            <img :src="currentImage" alt="大图" style="width: 100%;"/>
            <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
        </el-dialog>

        <!-- 视频模态框 -->
        <el-dialog :visible.sync="videoDialogVisible" width="80%">
            <video controls style="width: 100%; height: auto;">
                <source :src="currentVideo" type="video/mp4"/>
                您的浏览器不支持 HTML5 video 标签。
            </video>
            <span slot="footer" class="dialog-footer">
        <el-button @click="videoDialogVisible = false">取 消</el-button>
      </span>
        </el-dialog>

        <!--fenye-->
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 50]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount">
        </el-pagination>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                courseTableData: [],
                dialogFormVisible: false,//添加
                dialogFormVisible2: false,//修改
                dialogVisible: false, // 控制模态框的显示
                currentImage: '', // 当前显示的大图 URL
                videoDialogVisible: false, // 控制视频模态框的显示
                currentVideo: '', // 当前播放的视频 URL
                courseFormData: {
                    courseName: "",
                    courseDescription: "",
                    courseTime: '',
                    courseMount: '',
                    courseIntroduce: '',
                    applicablePopulation: '',
                    type_id: '',
                    learnHarvest: '',
                    subscriptionNotice: '',
                    teacher_id: '',
                    courseVideo: '',
                    courseImageUrl: "",
                    coursePrice: '',
                },

                courseName: '',
                value1: "",  //按时间搜索
                teacher: [], //老师的信息
                courseType: [],//书籍类型
                courseFormData2: [],//修改
                dialogImageUrl: "",
                disabled: false,
                dialogImg: false,
                formLabelWidth: '120px',

                videoUrl:"", // 视频地址
                imageUrl: "",
                totalCount: 0, // 总记录数
                pageSize: 10, // 每页显示的记录数
                currentPage: 1, // 当前页码
                isNavigating: false, // 路由导航状态标志
            };
        },
        methods: {



            openModal() {
                this.dialogFormVisible = !this.dialogFormVisible;
            },
            //时间
            getDateString(date) {
                // let str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                // return str;
                if (!date) {
                    return ""
                }
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },

            //搜索操作
            search() {

                if (!this.value1) {
                    this.value1="";
                }
                this.axios.get("/course/like", {
                    params: {
                        pageNo: this.currentPage,
                        pageSize: this.pageSize,
                        courseName: this.courseName,
                        startTime: this.getDateString(this.value1[0]),
                        endTime: this.getDateString(this.value1[1]),
                    }
                }).then(res => {

                    this.courseTableData = res.data.data.list; // 修改为正确的字段
                    this.courseTableData.forEach(item => {
                        // 假设 createtime 是一个数组
                        const [year, month, day, hour, minute, second] = item.updatetime; // 解构数组
                        // 拼接成时间格式字符串
                        item.updatetime = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`;
                    });
                    console.log(this.courseTableData)

                    this.totalCount = res.data.data.total;
                }).catch(err => {
                    "错误"
                })
            },

            //添加操作
            handleAdd() {
                this.axios.post('/course/add', {
                    coursename: this.courseFormData.courseName,
                    tabularchart: this.courseFormData.courseImageUrl,
                    coursetime: this.courseFormData.courseTime,
                    coursemount: this.courseFormData.courseMount,
                    courseintroduce: this.courseFormData.courseIntroduce,
                    applicablepopulation: this.courseFormData.applicablePopulation,
                    typeId: this.courseFormData.type_id,
                    teacherId: this.courseFormData.teacher_id,
                    learnharvest: this.courseFormData.learnHarvest,
                    subscriptionnotice: this.courseFormData.subscriptionNotice,
                    coursevideo: this.courseFormData.courseVideo,
                    courseprice: this.courseFormData.coursePrice,
                }).then((res) => {
                    if (res.data != null) {
                        this.$message({
                            message: '提交成功！',
                            type: 'success',
                            duration: 2000 // 2秒后自动消失
                        });
                    } else {
                        this.$message({
                            message: '提交失败，请重试！',
                            type: 'error',
                            duration: 2000 // 2秒后自动消失
                        });
                    }
                    console.log(res)
                    this.getCourse();
                }).catch(err => {

                })
                this.dialogFormVisible = false;
            },

            //上传视频

            handleVideoSuccess(res, file) {
                this.courseFormData.courseImageUrl = "http://localhost:8080/course/downImg?file=" + file.response.data
                console.log(this.courseTableData.courseImageUrl);
            },

            beforeVideoUpload(file) {
                this.videoUrl = URL.createObjectURL(file);

            },

            //修改视频
            handleVideoSuccess2(res, file) {
                this.courseFormData2.coursevideo = "http://localhost:8080/course/downImg?file=" + file.response.data
                console.log(this.courseFormData2.coursevideo);
            },

            beforeVideoUpload2(file) {
                this.videoUrl = URL.createObjectURL(file);

            },


            // 返回图片的地址
            handleAvatarSuccess(res, file) {
                this.courseFormData.courseVideo = "http://localhost:8080/course/downImg?file=" + file.response.data
                console.log(this.courseTableData.courseVideo);
            },

            beforeAvatarUpload(file) {
                this.imageUrl = URL.createObjectURL(file);

            },
            // 修改图片
            handleAvatarSuccess2(res, file) {
                this.courseFormData2.tabularchart = "http://localhost:8080/course/downImg?file=" + file.response.data
            },

            beforeAvatarUpload2(file) {
                this.imageUrl = URL.createObjectURL(file);
            },

            //删除操作
            handleDelete(index) {
                console.log("index:" + index)
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.axios.delete(`/course/delete?id=${index}`).then(response => {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getCourse();
                    }).catch(error => {
                        this.$message.error('删除失败，请重试'); // 处理删除失败的情况
                        console.error('删除失败', error);
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });


            },

            //修改数据回显
            updateCourse(data) {
                this.dialogFormVisible2 = true;
                console.log(data)
                this.courseFormData2 = data;
                // console.log(this.courseFormData2)

            },

            //修改操作
            handleUpdate() {
                this.axios.put('course/update', null, {
                    params: {
                        id: this.courseFormData2.id,
                        coursename: this.courseFormData2.coursename,
                        tabularchart: this.courseFormData2.tabularchart,
                        coursetime: this.courseFormData2.coursetime,
                        coursemount: this.courseFormData2.coursemount,
                        courseintroduce: this.courseFormData2.courseintroduce,
                        applicablepopulation: this.courseFormData2.applicablepopulation,
                        typeId: this.courseFormData2.typeId,
                        teacherId: this.courseFormData2.teacherId,
                        learnharvest: this.courseFormData2.learnharvest,
                        subscriptionnotice: this.courseFormData2.subscriptionNotice,
                        coursevideo: this.courseFormData2.coursevideo,
                        courseprice: this.courseFormData2.courseprice,

                    }
                }).then((res) => {
                    if (res.data != null) {
                        this.$message({
                            message: '提交成功！',
                            type: 'success',
                            duration: 2000 // 2秒后自动消失
                        });
                    } else {
                        this.$message({
                            message: '提交失败，请重试！',
                            type: 'error',
                            duration: 2000 // 2秒后自动消失
                        });
                    }
                    console.log(res)
                    this.getCourse();
                }).catch(err => {
                })
                this.dialogFormVisible2 = false;
            },


            //获得老师的所有信息
            getTeacherContent() {
                this.axios.get('/teacher/content').then((res) => {
                    console.log(res)
                    this.teacher = res.data.data
                    // console.log(this.teacher)
                })
            },

            //获得课程类型的所有信息
            getCourseTypeContent() {
                this.axios.get('/courseType/content').then((res) => {
                    this.courseType = res.data.data
                    // console.log(this.courseType)
                })
            },


            //切换每页的条数
            handleSizeChange(size) {
                this.pageSize = size;
                // 可以在这里重新获取数据
                this.search();
            },
            //切换页数
            handleCurrentChange(page) {
                this.currentPage = page;
                this.search();
            },

            //点击图片,显示大图效果
            showImage(imageUrl) {
                console.log("Image clicked:", imageUrl);
                this.currentImage = imageUrl; // 设置当前图片 URL
                this.dialogVisible = true; // 打开模态框
            },

           //点击图片,显示大图效果
            showImage2(imageUrl) {
                console.log("Image clicked:", imageUrl);
                this.currentImage2 = imageUrl; // 设置当前图片 URL
                this.dialogVisible = true; // 打开模态框
            },



            //点击视频,进行播放
            openVideoDialog(videoUrl) {
                this.currentVideo = videoUrl; // 设置当前视频 URL
                this.videoDialogVisible = true; // 打开视频模态框
            },
            getCourse() {
                this.axios.get(`/course/all?pageNo=${this.currentPage}&pageSize=${this.pageSize}`).then((res) => {
                    console.log(res)
                    this.courseTableData = res.data.data.list; // 修改为正确的字段

                    this.totalCount = res.data.data.total;
                    console.log(this.courseTableData);
                    // console.log(this.totalCount);
                }).catch(err => {
                    console.log("错误");
                });
            },

        },
        created() {
            this.getCourse();
            this.getCourseTypeContent();
            this.getTeacherContent();
        },
    }
</script>

<style scoped>
    .img-container {
        width: 70px;
        height: 70px;
        position: relative;
        border-radius: 20%;
    }

    .img-container > img {
        width: 100%;
        height: 100%;
        margin: 0 auto;
        object-fit: cover;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        border-radius: 20%;
    }

    .play-icon {
        font-size: 30px;
        line-height: 70px;
        margin: 0 auto;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409eff;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .img-container {
        width: 100px; /* 固定宽度 */
        height: 100px; /* 固定高度 */
        position: relative;
        border-radius: 20%;
        overflow: hidden; /* 确保超出部分被隐藏 */
        cursor: pointer; /* 鼠标悬停时显示为手型 */
    }

    .img-container > img {
        width: 100%; /* 使图片宽度适应容器 */
        height: 100%; /* 使图片高度适应容器 */
        object-fit: cover; /* 保持图片比例并填充容器 */
    }

    .shuru {
        width: 200px;
        height: 36px;
        padding: 0 15px;

    }

    .input {
        display: flex;
        flex-wrap: wrap;
        justify-content: left;
    }


</style>